const gulp = require('gulp');
const inject = require('gulp-inject-string');
const rollupTypescript = require('rollup-plugin-typescript2');
const rollup = require("rollup");
const concat = require('gulp-concat');
const through = require('through2');

function rollup_combie() {
    return rollup.rollup({
        input: './src/oimo/oimo.ts',
        treeshake: true,//建议忽略
        plugins: [
            rollupTypescript({
                noEmit: true,
                noEmitHelpers: true
            }),
        ]
    }).then(bundle => {
        return bundle.write({
            file: './tmp/oimo.js',
            format: 'iife',
            name: 'OIMO',
            sourcemap: true
        });
    });
}
gulp.task("编译ts", rollup_combie);

gulp.task("增加window导出", function () {
    return gulp.src('./tmp/oimo.js')
        .pipe(inject.replace('export { OIMO };', 'window.OIMO = OIMO;'))
        .pipe(gulp.dest('./bin/libs'))
        .pipe(gulp.dest('./out'))
});

gulp.task('oimo-拷贝map', function () {
    return gulp.src('./tmp/oimo.js.map')
        .pipe(gulp.dest('./bin/libs'))
        .pipe(gulp.dest('./out'))
});

gulp.task("合并d.ts", function () {
    return gulp.src([
        './tmp/oimo/*/*/*/*/*/*.d.ts',
        './tmp/oimo/*/*/*/*/*.d.ts',
        './tmp/oimo/*/*/*/*.d.ts',
        './tmp/oimo/*/*/*.d.ts',
        './tmp/oimo/*/*.d.ts',
        './tmp/oimo/*.d.ts'])
        .pipe(remove_unused())
        .pipe(concat('oimo.d.ts'))
        .pipe(inject.append('}'))
        .pipe(inject.prepend('declare namespace OIMO {'))
        .pipe(gulp.dest('./libs'));
});

function remove_unused(options) {
    var steam = through.obj(function (file, enc, cb) {
        if (file.isNull()) {
            console.log("isNull");
        } else if (file.isStream()) {
            console.log("isStream");
        } else if (file.isBuffer()) {
            let allStr = file.contents.toString();
            while (allStr.indexOf('declare ') > -1) {
                allStr = allStr.replace('declare ', '');
            }
            while (allStr.search(/import\s.*;/gm) > -1) {
                allStr = allStr.replace(/import\s.*;/gm, '');
            }
            while (allStr.search(/export\s.*;/gm) > -1) {
                allStr = allStr.replace(/export\s.*;/gm, '');
            }
            while (allStr.search(/export /gm) > -1) {
                allStr = allStr.replace(/export /gm, '');
            }
            file.contents = Buffer.from(allStr);
        }
        this.push(file);
        cb();
    })
    return steam;
}